import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
 const cartList = ref([])
 const addItem= (playload)=>{
     const index=cartList.value.findIndex(item=>item.id==playload.id)
     if(index > -1)
     {
        cartList.value[index].count++
     }else{
        cartList.value.push({
            ...playload,
            count:1,
            checked:false
        })
     }
 }

  //删除
  const delItem =(id)=>{
    cartList.value=cartList.value.filter(item=>item.id !=id)
  }
 
  const totalCount = computed(()=>{
     let res = 0
     cartList.value.forEach(item=>{
        res +=item.count
     })
     return res
  })
   const totalPrice = computed(()=>{
     let res = 0
     cartList.value.forEach(item=>{
        if(item.checked==true)
        {
               res +=item.count * item.price
        }
      
     })
     return res
  })
  return {cartList,addItem,delItem ,totalCount,totalPrice }
},{
    persist:true
})